﻿#include "login.h"
#include "ui_login.h"
#include "connect.h"
#include <QMessageBox>//弹出对话框
#include <QInputDialog>
#include <QSqlError>//数据库错误相关
#include <QSqlDatabase>//连接数据库相关
#include <QSqlQuery>//执行sql语句相关
#include <QDebug>//程序输出，相当于print
#include <QSettings>//自动登录相关
#include <QTextCodec>
#include "database_home.h"
#include "ui_database_home.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "fhmainwindow.h"
#include "ui_fhmainwindow.h"

#include "yrmainwindow.h"
#include "ui_yrmainwindow.h"
#define CONFIGPATH (QCoreApplication::applicationDirPath() + "config.ini") //设置一个用于存储的ini文件
//static QString userTyp="";

login::login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);
    loginInit();//登录界面初始化
}

login::~login()
{
    delete ui;
}

void login::loginInit()
{
    QSettings setting(CONFIGPATH, QSettings::IniFormat); // 打开存放登录信息的ini文件
    setting.setIniCodec(QTextCodec::codecForName("UTF-8")); // 设置编码格式，如果这里有中文，读和写的时候都要保持一致
    QString isremember = setting.value("login/isremember").toString(); // 是否选择了记住密码
    QString name = setting.value("login/username").toString(); // 账号
    QString password = setting.value("login/password").toString(); // 密码
    ui->lineEdit_user->setText(name); // 显示上一次登录的账号名
    if (isremember == "true") // 记住密码
    {
        ui->lineEdit_pwd->setText(password); // 密码写在密码输入框
        ui->checkBox_rempwd->setChecked(true); // 记住密码那里打√
        ispassword = true; // 记住密码
    }
    else
    {
        ui->checkBox_rempwd->setChecked(false); // 记住密码那里不打√
        ispassword = false; // 不记住密码
    }
    //输出可用数据库
    //    qDebug()<<"available drivers:";
    //    QStringList drivers = QSqlDatabase::drivers();
    //    foreach(QString driver, drivers)
    //        qDebug()<<driver;

}

//登录按钮
void login::on_pushButton_login_clicked()
{
    createConnection();
    mymodel_login = new QSqlTableModel(this);
    mymodel_login->setTable("UserManagement");//设置表的名称
    mymodel_login->setEditStrategy(QSqlTableModel::OnManualSubmit);// 设置编辑策略

    //获取用户名，密码,类型
    QString user_name = ui->lineEdit_user->text().trimmed();//trimmed去除开头结尾的空白字符串
    QString user_pwd = ui->lineEdit_pwd->text().trimmed();
    QString user_type = ui->comboBox_ID->currentText().trimmed();
    if(user_name.isEmpty())
    {
        QMessageBox::about(this, "注意！", "用户名不能为空");
        return;
    }

    if(user_pwd.isEmpty())
    {
        QMessageBox::about(this, "注意！", "用户密码不能为空");
        return;
    }


    QSqlQuery query;
    mymodel_login->setFilter(QString("name = '%1'").arg(user_name));//可选择使用
    QString str="select count(id) from UserManagement where name='"+user_name+"' and password='"+user_pwd+"'and type='"+user_type+"'";
    query.exec(str);
    query.next();
    int count = query.value(0).toInt();
    qDebug()<< query.value(0).toInt()<< query.value(1).toString()<< query.value(2).toString();
    if(count == 1)
    {
        qDebug() <<user_type <<"："<< user_name << "logining...";
        QSettings writeini(CONFIGPATH, QSettings::IniFormat); // 打开ini文件
        writeini.setIniCodec(QTextCodec::codecForName("UTF-8")); // 设置编码格式
        if (ispassword) // 选择保存密码
        {
            writeini.setValue("login/isremember", "true"); // 写ini文件时记录为true
        }
        else // 不保存密码
        {
            writeini.setValue("login/isremember", "false"); // 写ini文件时记录为false
        }
        writeini.setValue("login/username", user_name); // 把账号写入ini文件
        writeini.setValue("login/password", user_pwd); // 把密码写入ini文件
        userType=user_type;
        //accept();
        if(ui->comboBox_DB->currentText().trimmed() == "辐射引燃和燃烧危险性数据库_old"){
            MainWindow *w = new MainWindow();
            w->setWindowTitle("森林-城镇交界域典型建筑材料的引燃和燃烧危险性数据库--辐射引燃和燃烧危险性数据库");
            w->show();
        }else if ((ui->comboBox_DB->currentText().trimmed() == "飞火引燃危险性数据库")) {
            //QMessageBox::about(this, "提示！", "飞火引燃危险性数据库开发中！");
            if (user_name != "root" && !user_name.startsWith("adminqb-") && !user_name.startsWith("userqb-") && !user_name.startsWith("adminfh-")
                    && !user_name.startsWith("userfh-") && user_name != "admin" && user_name != "user") {
                QMessageBox::about(this, "提示！", "请检查用户名前缀和权限！");
                return ;
            } else {
                this->close();
                FHMainWindow *fhw = new FHMainWindow();
                fhw->setWindowTitle(tr("森林-城镇交界域典型建筑材料的引燃和燃烧危险性数据库--飞火引燃危险性数据库"));
                fhw->show();
            }
        }else if((ui->comboBox_DB->currentText().trimmed() == "辐射引燃危险性和燃烧特性数据库")) {
            if (user_name != "root" && !user_name.startsWith("adminqb-") && !user_name.startsWith("userqb-") && !user_name.startsWith("adminfs-")
                    && !user_name.startsWith("userfs-") && user_name != "admin" && user_name != "user") {
                QMessageBox::about(this, "提示！", "请检查用户名前缀和权限！");
                return ;
            } else {
                this->close();
                YRMainWindow *yrw = new YRMainWindow();
                yrw->setWindowTitle(tr("森林-城镇交界域典型建筑材料的引燃和燃烧危险性数据库--辐射引燃危险性和燃烧特性数据库"));
                yrw->setWindowIcon(QIcon(":/images/fire.png"));
                yrw->show();
            }
        }
    }
    else
    {
        QMessageBox::information(this,"提示","用户类型、用户名或密码错误，请检查！");
    }

}

void login::on_pushButton_forgivePWD_clicked()
{
    if (ui->lineEdit_user->text().trimmed().isEmpty() || ui->lineEdit_user->text().trimmed() != "root") {
        QMessageBox::information(this,"提示","请联系高级管理员");
    } else {
        //验证root的密码，如果通过，则可以强制修改输入的用户名的密码
        QDialog forgivePwdDialog(this);
        forgivePwdDialog.setWindowTitle("强制修改密码");
        forgivePwdDialog.setFixedSize(300, 250);

        QLabel *rootPwdLabel = new QLabel("请输入 root 密码:", &forgivePwdDialog);
        QLineEdit *rootPwdEdit = new QLineEdit(&forgivePwdDialog);
        rootPwdEdit->setEchoMode(QLineEdit::Password);

        QLabel *targetUserLabel = new QLabel("目标用户名:", &forgivePwdDialog);
        QLineEdit *targetUserEdit = new QLineEdit(&forgivePwdDialog);

        QLabel *newPwdLabel = new QLabel("新密码:", &forgivePwdDialog);
        QLineEdit *newPwdEdit = new QLineEdit(&forgivePwdDialog);
        newPwdEdit->setEchoMode(QLineEdit::Password);

        QPushButton *okButton = new QPushButton("确定", &forgivePwdDialog);
        QPushButton *cancelButton = new QPushButton("取消", &forgivePwdDialog);

        QVBoxLayout *layout = new QVBoxLayout(&forgivePwdDialog);
        layout->addWidget(rootPwdLabel);
        layout->addWidget(rootPwdEdit);
        layout->addWidget(targetUserLabel);
        layout->addWidget(targetUserEdit);
        layout->addWidget(newPwdLabel);
        layout->addWidget(newPwdEdit);

        QHBoxLayout *buttonLayout = new QHBoxLayout;
        buttonLayout->addWidget(okButton);
        buttonLayout->addWidget(cancelButton);
        layout->addLayout(buttonLayout);

        connect(okButton, &QPushButton::clicked, &forgivePwdDialog, [&]() {
            QString rootPwd = rootPwdEdit->text().trimmed();
            QString targetUser = targetUserEdit->text().trimmed();
            QString newPwd = newPwdEdit->text().trimmed();

            if (rootPwd.isEmpty() || targetUser.isEmpty() || newPwd.isEmpty()) {
                QMessageBox::warning(&forgivePwdDialog, "错误", "所有字段不能为空！");
                return;
            }

            if (targetUser == "root") {
                QMessageBox::warning(&forgivePwdDialog, "错误", "root用户，请使用修改密码功能！");
                return;
            }

            createConnection();
            QSqlQuery query;

            // 验证 root 密码
            QString queryStr = QString("SELECT password FROM UserManagement WHERE name='root'");
            if (!query.exec(queryStr) || !query.next()) {
                QMessageBox::critical(&forgivePwdDialog, "错误", "查询 root 密码失败！\n" + query.lastError().text());
                return;
            }

            if (query.value(0).toString() != rootPwd) {
                QMessageBox::warning(&forgivePwdDialog, "错误", "root 密码错误！");
                return;
            }

            // 检查目标用户是否存在
            queryStr = QString("SELECT name FROM UserManagement WHERE name='%1'").arg(targetUser);
            if (!query.exec(queryStr) || !query.next()) {
                QMessageBox::warning(&forgivePwdDialog, "错误", "目标用户不存在！");
                return;
            }

            // 更新目标用户的密码
            queryStr = QString("UPDATE UserManagement SET password='%1' WHERE name='%2'")
                    .arg(newPwd)
                    .arg(targetUser);
            if (!query.exec(queryStr)) {
                QMessageBox::critical(&forgivePwdDialog, "错误", "密码更新失败！\n" + query.lastError().text());
                return;
            }

            QMessageBox::information(&forgivePwdDialog, "成功", "目标用户密码修改成功！");
            forgivePwdDialog.accept();
        });

        connect(cancelButton, &QPushButton::clicked, &forgivePwdDialog, &QDialog::reject);

        forgivePwdDialog.exec();
    }
}

//记住密码
void login::on_checkBox_rempwd_clicked()
{
    // 根据是否记住密码改变标志位
    ispassword = ui->checkBox_rempwd->isChecked();
}


void login::on_commandLinkButton_clicked()
{
    this->close();
    database_home *dw = new database_home();
    dw->setWindowTitle("森林-城镇交界域典型建筑材料的引燃和燃烧危险性数据库");
    dw->show();
}

void login::on_pushButton_changePWD_clicked()
{
    // 弹出一个对话框，用于输入旧密码、新密码和再次输入的新密码
    QDialog changePwdDialog(this);
    changePwdDialog.setWindowTitle("修改密码");
    changePwdDialog.setFixedSize(300, 250);

    QLabel *userLabel = new QLabel(QString("当前用户名: %1").arg(ui->lineEdit_user->text().trimmed()), &changePwdDialog);
    userLabel->setStyleSheet("font-weight: bold;"); // 设置加粗字体

    QLabel *oldPwdLabel = new QLabel("旧密码:", &changePwdDialog);
    QLineEdit *oldPwdEdit = new QLineEdit(&changePwdDialog);
    oldPwdEdit->setEchoMode(QLineEdit::Password);

    QLabel *newPwdLabel = new QLabel("新密码:", &changePwdDialog);
    QLineEdit *newPwdEdit = new QLineEdit(&changePwdDialog);
    newPwdEdit->setEchoMode(QLineEdit::Password);

    QLabel *confirmPwdLabel = new QLabel("再次输入新密码:", &changePwdDialog);
    QLineEdit *confirmPwdEdit = new QLineEdit(&changePwdDialog);
    confirmPwdEdit->setEchoMode(QLineEdit::Password);

    QPushButton *okButton = new QPushButton("确定", &changePwdDialog);
    QPushButton *cancelButton = new QPushButton("取消", &changePwdDialog);

    QVBoxLayout *layout = new QVBoxLayout(&changePwdDialog);
    layout->addWidget(userLabel);
    layout->addWidget(oldPwdLabel);
    layout->addWidget(oldPwdEdit);
    layout->addWidget(newPwdLabel);
    layout->addWidget(newPwdEdit);
    layout->addWidget(confirmPwdLabel);
    layout->addWidget(confirmPwdEdit);

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);
    layout->addLayout(buttonLayout);

    connect(okButton, &QPushButton::clicked, &changePwdDialog, [&]() {
        QString oldPwd = oldPwdEdit->text().trimmed();
        QString newPwd = newPwdEdit->text().trimmed();
        QString confirmPwd = confirmPwdEdit->text().trimmed();
        QString userName = ui->lineEdit_user->text().trimmed();

        if (oldPwd.isEmpty() || newPwd.isEmpty() || confirmPwd.isEmpty()) {
            QMessageBox::warning(&changePwdDialog, "错误", "所有字段不能为空！");
            return;
        }

        if (newPwd != confirmPwd) {
            QMessageBox::warning(&changePwdDialog, "错误", "两次输入的新密码不一致！");
            return;
        }

        if (userName == "root") {
            QMessageBox::warning(&changePwdDialog, "错误", "抱歉，root用户暂不支持修改密码！");
            return;
        }

        createConnection();

        QSqlQuery query;
        QString queryStr = QString("SELECT password FROM UserManagement WHERE name='%1'")
                .arg(userName);

        if (!query.exec(queryStr)) {
            QMessageBox::critical(&changePwdDialog, "错误", "查询旧密码失败！\n" + query.lastError().text());
            qDebug() << "Query Failed:" << queryStr;
            return;
        }

        if (query.next()) {
            QString currentPwd = query.value(0).toString();
            qDebug() << "数据库中的旧密码:" << currentPwd;

            if (currentPwd != oldPwd) {
                QMessageBox::warning(&changePwdDialog, "错误", "旧密码错误！");
                return;
            }

            queryStr = QString("UPDATE UserManagement SET password='%1' WHERE name='%2'")
                    .arg(newPwd)
                    .arg(userName);

            if (!query.exec(queryStr)) {
                QMessageBox::critical(&changePwdDialog, "错误", "密码更新失败！\n" + query.lastError().text());
                qDebug() << "Update Query Failed:" << queryStr;
                return;
            }

            QMessageBox::information(&changePwdDialog, "成功", "密码修改成功！");
            changePwdDialog.accept();
        } else {
            QMessageBox::warning(&changePwdDialog, "错误", "用户名不存在！");
            qDebug() << "用户名不存在:" << userName;
        }
    });

    connect(cancelButton, &QPushButton::clicked, &changePwdDialog, &QDialog::reject);

    changePwdDialog.exec();
}


void login::on_pushButton_register_clicked()
{
    // 创建一个新的窗口用于注册
    QDialog registerDialog(this);
    registerDialog.setWindowTitle("用户注册");

    QVBoxLayout *layout = new QVBoxLayout(&registerDialog);

    // 用户级别下拉框
    QLabel *levelLabel = new QLabel("选择用户级别：");
    QComboBox *levelComboBox = new QComboBox();
    levelComboBox->addItems({"", "adminqb-", "userqb-", "adminfs-", "userfs-", "adminfh-", "userfh-"});
    layout->addWidget(levelLabel);
    layout->addWidget(levelComboBox);

    // 注册用户名输入框
    QLabel *userLabel = new QLabel("用户名：");
    QLineEdit *userEdit = new QLineEdit();
    layout->addWidget(userLabel);
    layout->addWidget(userEdit);

    // 当下拉框选项改变时更新用户名输入框
    connect(levelComboBox, &QComboBox::currentTextChanged, [&](const QString &text) {
        userEdit->setText(text);
    });

    // 密码输入框
    QLabel *passwordLabel = new QLabel("密码：");
    QLineEdit *passwordEdit = new QLineEdit();
    passwordEdit->setEchoMode(QLineEdit::Password);
    layout->addWidget(passwordLabel);
    layout->addWidget(passwordEdit);

    // 重复密码输入框
    QLabel *confirmPasswordLabel = new QLabel("确认密码：");
    QLineEdit *confirmPasswordEdit = new QLineEdit();
    confirmPasswordEdit->setEchoMode(QLineEdit::Password);
    layout->addWidget(confirmPasswordLabel);
    layout->addWidget(confirmPasswordEdit);

    // 按钮组
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *confirmButton = new QPushButton("确认");
    QPushButton *cancelButton = new QPushButton("取消");
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);
    layout->addLayout(buttonLayout);

    // 用户统计
    QLabel *statsLabel = new QLabel();
    layout->addWidget(statsLabel);

    createConnection();

    auto updateStats = [&]() {
        QSqlQuery query;
        query.exec("SELECT type, COUNT(*) FROM UserManagement GROUP BY type");

        int rootCount = 0, adminCount = 0, userCount = 0;
        while (query.next()) {
            QString type = query.value(0).toString();
            int count = query.value(1).toInt();
            if (type == "Root")
                rootCount += count;
            else if (type == "Administrator")
                adminCount += count;
            else if (type == "User")
                userCount += count;
        }

        statsLabel->setText(
                    QString("当前系统用户统计：\nRoot级用户：%1个\nAdministrator级用户：%2个\nUser级用户：%3个")
                    .arg(rootCount)
                    .arg(adminCount)
                    .arg(userCount)
                    );
    };
    updateStats();

    // 确认按钮逻辑
    connect(confirmButton, &QPushButton::clicked, [&]() {
        QString userType = levelComboBox->currentText();
        QString userName = userEdit->text();
        QString password = passwordEdit->text();
        QString confirmPassword = confirmPasswordEdit->text();

        if (userName.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            QMessageBox::warning(&registerDialog, "警告", "请填写所有必填字段！");
            return;
        }

        QStringList nameList = {"adminqb-", "userqb-", "adminfs-", "userfs-", "adminfh-", "userfh-"};

        // 检查用户名是否以非法前缀开头
        bool hasValidPrefix = false;
        for (const QString &prefix : nameList) {
            if (userName.startsWith(prefix)) {
                hasValidPrefix = true;
                break;
            }
        }

        if (!hasValidPrefix) {
            QMessageBox::warning(&registerDialog, "警告", "用户名前缀非法，请检查");
            return;
        }

        if (password != confirmPassword) {
            QMessageBox::warning(&registerDialog, "警告", "两次输入的密码不一致！");
            return;
        }

        // 验证用户名是否重名
        QSqlQuery query;
        query.prepare("SELECT COUNT(*) FROM UserManagement WHERE name = :name");
        query.bindValue(":name", userName);

        if (!query.exec()) {
            QMessageBox::critical(&registerDialog, "错误", "检查用户名是否重名时发生错误！");
            return;
        }

        query.next();
        if (query.value(0).toInt() > 0) {
            QMessageBox::warning(&registerDialog, "警告", "用户名已存在，请更换用户名！");
            return;
        }

        // 验证Root密码
        bool authenticated = false;
        bool ok;
        QString rootPassword = QInputDialog::getText(&registerDialog, "验证Root密码", "请输入Root密码：", QLineEdit::Password, "", &ok);

        if (ok && !rootPassword.isEmpty()) {
            query.prepare("SELECT COUNT(*) FROM UserManagement WHERE name='root' AND password=:password");
            query.bindValue(":password", rootPassword);

            if (query.exec() && query.next() && query.value(0).toInt() == 1) {
                authenticated = true;
            }
        }

        if (!authenticated) {
            QMessageBox::warning(&registerDialog, "警告", "Root密码验证失败！");
            return;
        }

        // 插入新用户
        query.prepare("INSERT INTO UserManagement (id, name, password, type) VALUES (NULL, :name, :password, :type)");
        query.bindValue(":name", userName);
        query.bindValue(":password", password);
        query.bindValue(":type", userType.contains("admin") ? "Administrator" : "User");

        if (!query.exec()) {
            QMessageBox::critical(&registerDialog, "错误", "注册失败，请检查数据库配置！");
            return;
        }

        QMessageBox::information(&registerDialog, "成功", "注册成功！");
        updateStats();
    });

    // 取消按钮逻辑
    connect(cancelButton, &QPushButton::clicked, [&]() {
        registerDialog.reject();
    });

    registerDialog.exec();
}


void login::on_pushButton_manage_clicked()
{
    // 验证出厂密码
    bool authenticated = false;
    bool ok;
    QString rootPassword = QInputDialog::getText(this, "验证出厂密码", "请输入出厂密码：", QLineEdit::Password, "", &ok);

    if (ok && !rootPassword.isEmpty()) {

        if (rootPassword == "Scfri119#WUI" || rootPassword == "159753") {
            authenticated = true;
        }
    }

    if (!authenticated) {
        QMessageBox::warning(this, "警告", "出厂密码验证失败！");
        return;
    }

    // 创建用户管理窗口
    QDialog manageDialog(this);
    manageDialog.setWindowTitle("用户管理");
    manageDialog.setMinimumSize(600, 600);

    QVBoxLayout *layout = new QVBoxLayout(&manageDialog);

    // 用户列表视图
    QLabel *userListLabel = new QLabel("用户列表：");
    QTableView *userTableView = new QTableView();
    layout->addWidget(userListLabel);
    layout->addWidget(userTableView);

    createConnection();

    // 数据模型设置
    QSqlTableModel *userModel = new QSqlTableModel(this);
    userModel->setTable("UserManagement");
    userModel->setEditStrategy(QSqlTableModel::OnManualSubmit); // 编辑后需手动提交
    userTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    userModel->select(); // 加载数据
    userTableView->setModel(userModel);
    userTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    userTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    userTableView->resizeColumnsToContents();
    userTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 添加右键菜单
    userTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(userTableView, &QTableView::customContextMenuRequested, [&](const QPoint &pos) {
        QMenu contextMenu(userTableView);
        QAction *editNameAction = new QAction("更改用户名", &contextMenu);
        QAction *editPasswordAction = new QAction("更改密码", &contextMenu);
        QAction *deleteUserAction = new QAction("删除用户", &contextMenu);

        //contextMenu.addAction(editNameAction);
        contextMenu.addAction(editPasswordAction);
        contextMenu.addAction(deleteUserAction);

        // 获取选中的行
        QModelIndex index = userTableView->indexAt(pos);
        if (!index.isValid())
            return;

        QString userName = userModel->data(userModel->index(index.row(), 1)).toString();

        // 禁止删除 Root 用户
        if (userName == "root") {
            deleteUserAction->setEnabled(false);
        }

        // 更改用户名
        connect(editNameAction, &QAction::triggered, [&]() {
            bool ok;
            QString newUserName = QInputDialog::getText(&manageDialog, "更改用户名",
                                                        "输入新的用户名：", QLineEdit::Normal,
                                                        userName, &ok);
            if (ok && !newUserName.isEmpty()) {
                userModel->setData(userModel->index(index.row(), 1), newUserName);
                if (!userModel->submitAll()) {
                    QMessageBox::critical(&manageDialog, "错误", "用户名更改失败！");
                    userModel->revertAll();
                } else {
                    QMessageBox::information(&manageDialog, "成功", "用户名已更改！");
                }
            }
        });

        // 更改密码
        connect(editPasswordAction, &QAction::triggered, [&]() {
            bool ok;
            QString newPassword = QInputDialog::getText(&manageDialog, "更改密码",
                                                        "输入新的密码：", QLineEdit::Password,
                                                        "", &ok);
            if (ok && !newPassword.isEmpty()) {
                userModel->setData(userModel->index(index.row(), 2), newPassword);
                if (!userModel->submitAll()) {
                    QMessageBox::critical(&manageDialog, "错误", "密码更改失败！");
                    userModel->revertAll();
                } else {
                    QMessageBox::information(&manageDialog, "成功", "密码已更改！");
                }
            }
        });

        // 删除用户
        connect(deleteUserAction, &QAction::triggered, [&]() {
            int ret = QMessageBox::question(&manageDialog, "确认",
                                            QString("确定删除用户 '%1' 吗？").arg(userName),
                                            QMessageBox::Yes | QMessageBox::No);
            if (ret == QMessageBox::Yes) {
                userModel->removeRow(index.row());
                if (!userModel->submitAll()) {
                    QMessageBox::critical(&manageDialog, "错误", "用户删除失败！");
                    userModel->revertAll();
                } else {
                    QMessageBox::information(&manageDialog, "成功", "用户已删除！");
                }
            }
        });

        // 显示菜单
        contextMenu.exec(userTableView->viewport()->mapToGlobal(pos));
    });

    // 关闭按钮
    QPushButton *closeButton = new QPushButton("关闭");
    layout->addWidget(closeButton);
    connect(closeButton, &QPushButton::clicked, [&]() {
        manageDialog.accept();
    });

    manageDialog.exec();
}
